package org.example.sportdemo.utils;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.UUID;

public class OSSUtils {

    private static String endpoint = "https://oss-cn-beijing.aliyuncs.com";

    public static String AccessKey_ID="LTAItZkVdx0jvJXx";
    public static String AccessKey_Secret="BGC3VrtgNiQbVbQxul6BaY0lUl0ELU";

    public static String BucketName = "work0304";

    public static String path = "https://work0304.oss-cn-beijing.aliyuncs.com/";


    /**
     *
     * @param file  要上传的文件
     * @return
     */
    public static String putObject(MultipartFile file){
        //创建OSS客户端
        OSS ossClient = new OSSClientBuilder().build(endpoint,AccessKey_ID,AccessKey_Secret);

        //对上传的文件进行重名
        String updateName = updateName(file.getOriginalFilename());
        //上传
        try {
            ossClient.putObject(BucketName,updateName,new ByteArrayInputStream(file.getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

        //关闭客户端
        ossClient.shutdown();
        //返回完整路径
        return path+updateName;
    }

    /**
     * 对上传的文件进行重名
     */
    public static String updateName(String oldName){
        //获取文件后缀名
        String suffixName = getFileName(oldName);
        //重命名文件
        String newName = UUID.randomUUID().toString()+System.currentTimeMillis()+suffixName;
        return newName;
    }


    /**
     * 获取文件后缀名
     */
    public static String getFileName(String fileName){
        //1.png 1.txt
        //获取.的位置
        int i = fileName.lastIndexOf(".");
        //根据位置进行截取
        String s = fileName.substring(i);
        return s;
    }
}
